#include <iostream>
#include <string>
#include <unordered_map>
#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>

/*
    在线字典翻译服务器
*/
class DictServer
{
public:
    DictServer(int port = 8888): _server(&_baseloop, muduo::net::InetAddress("0.0.0.0", port), "DictServer", muduo::net::TcpServer::kReusePort) // kReusePort：表示端口复用
    {
        // 设置连接事件回调（给_server, _server会设置给_baseloop）
        _server.setConnectionCallback(std::bind(&DictServer::onConnection, this, std::placeholders::_1));

        // 设置消息事件回调（给_server, _server会设置给_baseloop）
        _server.setMessageCallback(std::bind(&DictServer::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    void start()
    {
        // 开始监听
        _server.start();

        // 开始事件循环
        _baseloop.loop();
    }

private:
    // 连接建立或断开时的处理函数
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected())
            std::cout << "onConnection: " << conn->peerAddress().toIpPort() << " -> " << conn->localAddress().toIpPort() << std::endl;
        else
            std::cout << "onConnection: " << conn->peerAddress().toIpPort() << " -> " << conn->localAddress().toIpPort() << " is down" << std::endl;
    }

    // 连接读写事件处理函数
    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp)
    {
        static std::unordered_map<std::string, std::string> dictMap = {{"hello",  "你好"}, {"world",  "世界"}};
        std::string msg = buf->retrieveAllAsString(); // 读取缓冲区中的数据（此处没有做粘包处理，简单的demo）
        std::string res;
        auto it = dictMap.find(msg);
        if (it != dictMap.end())
            res = it->second;
        else
            res = "unknown";
        conn->send(res);
    }

private:
    // 注意成员属性的声明顺序
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;
};

int main()
{
    DictServer ds(8888);
    ds.start();
    return 0;
}